//回单管理

/**
 * 总视图
 */
interface IReceiptManagentViewModel extends IBaseViewModel<IReceiptManagentQueryTerms>{
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<carryOrderListResponse>;
    /**
     * 时间日期格式
     */
    dateFormat: "{format:'YYYY.MM.DD HH:mm'}";
    /**
     * 列表高度设置
     */
    heightA:number;
    /**
     * 合同状态下拉
     */
    contractStatusDropDown:ValueListItemResponse[];
    /**
     * 油卡状态下拉
     */
    oilCardStatusDropDown:ValueListItemResponse[];
    /**
     * 回单状态下拉
     */
    receiptPriceStatusDropDown:ValueListItemResponse[];
    /**
     * 客服专员下拉
     */
    customerServiceDropDown:EmployeeListItemResponse[];
    /**
     * 回单管理按钮启用禁用
     */
    canReceiptOrderDetail:boolean;
    /**
     * 回单管理事件
     */
    receiptOrderDetail:() => void;
    /**
     * 导出报表按钮启用禁用
     */
    canExport:boolean;  
    
    //11.1新增
    /**
     * 结算单据状态下拉
     */
    receiptBillStatusDropDown:ValueListItemResponse[]
}


/**
 * 查询条件
 */
interface IReceiptManagentQueryTerms{
    /**
     * 客户单位
     */
    clientName:string;
    /**
     * 车牌号
     */
    carCode:string;
    /**
     * 线路地址
     */
    route:string;
    /**
     * 合同号
     */
    contractNum:string;
    /**
     * 发货起始时间
     */
    shipStartTime:string;
    /**
     * 发货结束时间
     */
    shipEndTime:string;
    /**
     * 合同状态
     */
    contractStatus:string;
    /**
     * 油卡状态
     */
    oilCardStatus:string;
    /**
     * 回单状态
     */
    receiptPriceStatus:string;
    /**
     * 承运商
     */
    carrierName:string;
    /**
     * 客服专员编号
     */
    customerServiceId:string;
    /**
     * 发货地址
     */
    shipAddress:string;
    /**
     * 送货地址
     */
    deliverAddress:string;

    //11.1新增
    /**
     * 结算单据状态
     */
    receiptBillStatus:string;
}

class ReceiptManagentController extends ListController<IReceiptManagentViewModel,IReceiptManagentQueryTerms>{

    gridApi: uiGrid.IGridApiOf<carryOrderListResponse>;
    /**
     * 选中的承运单id
     */
    selectCarryOrderId:string;
    
    orderBy:number = 0;
    asc:boolean = true;
    skip:number=0;

    constructor($scope:IReceiptManagentViewModel,private authorizationService:IAuthorizationService,private routeService:routeService,private $state: angular.ui.IStateService,private orderService:IorderService,private valueService:IValueService,private employeeService:IEmployeeService,private $ngBootbox: BootboxService,private $location:ng.ILocationService,private exportService:IexportService){
        super($scope);
        this.init();
    }

    init():void{
        super.init();
        this.selectCarryOrderId = "";
		this.$scope.canReceiptOrderDetail = false;  
		this.$scope.canExport = false;
        this.$scope.receiptOrderDetail = this.receiptOrderDetail;

        this.receiptOrder();
        this.exportOrder();


        this.$scope.queryTerms = {
            clientName:"",
            carCode:"",
            route:"",
            contractNum:"",
            shipStartTime:"",
            shipEndTime:"",
            contractStatus:"",
            oilCardStatus:"",
            receiptPriceStatus:"",
            carrierName:"",
            customerServiceId:"",
            shipAddress:"",
            deliverAddress:"",
            receiptBillStatus:""
        }

         this.$scope.gridOptions = {
            data: [],
			enableRowSelection: true,
            multiSelect:false,
			enableRowHeaderSelection: false,
			enableSelectAll: false,
			paginationPageSizes: [10, 20, 30],
			useExternalPagination: true,
			useExternalSorting: true,
			enableColumnResizing: true,
			columnDefs: [
                { displayName: "订单编号", field: 'orderId', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, cellTemplate: '<div ng-repeat="item in row.entity.orderList" style="height:39px!important; white-space: pre-wrap!important; text-overflow:ellipsis; overflow:hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; word-wrap: break-word; padding:3px 2px;">{{item.orderId}}</div>', width: '6%' },
                { displayName: "客户单位", field: 'clientName', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, cellTemplate: '<div ng-repeat="item in row.entity.orderList" style="height:39px!important; white-space: pre-wrap!important; text-overflow:ellipsis; overflow:hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; word-wrap: break-word; padding:3px 2px;">{{item.clientName}}</div>', width: '10%' },
                { displayName: "发货地址", field: 'startAddress', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, cellTemplate: '<div ng-repeat="item in row.entity.orderList" style="height:39px!important; white-space: pre-wrap!important; text-overflow:ellipsis; overflow:hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; word-wrap: break-word; padding:3px 2px;">{{item.startAddress}}</div>', width: '10%' },
                { displayName: '送货地址', field: 'endAddress', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, enableSorting: false, cellTemplate: '<div ng-repeat="item in row.entity.orderList" style="height:39px!important; white-space: pre-wrap!important; text-overflow:ellipsis; overflow:hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; word-wrap: break-word; padding:3px 2px;">{{item.endAddress}}</div>', width: '10%' },
                { displayName: '货物数量', field: 'goodsNum', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, cellTemplate: '<div ng-repeat="item in row.entity.orderList" style="height:39px!important; white-space: pre-wrap!important; text-overflow:ellipsis; overflow:hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; word-wrap: break-word; padding:3px 2px;">{{item.goodsNum}}</div>', width: '6%' },
                { displayName: '发货时间', field: 'shipTime', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, cellTemplate: '<div ng-repeat="item in row.entity.orderList" style="height:39px!important; white-space: pre-wrap!important; text-overflow:ellipsis; overflow:hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; word-wrap: break-word; padding:3px 2px;">{{item.shipTime}}</div>', width: '10%' },
				{ displayName: '回单状态', field: 'receiptOrderDegree', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, cellTemplate: '<div ng-repeat="item in row.entity.orderList" style="height:39px!important; white-space: pre-wrap!important; text-overflow:ellipsis; overflow:hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; word-wrap: break-word; padding:3px 2px;">{{item.receiptStatus}}</div>' },
				{ displayName: '客服专员', field: 'customerServiceOfficer', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, cellTemplate: '<div ng-repeat="item in row.entity.orderList" style="height:39px!important; white-space: pre-wrap!important; text-overflow:ellipsis; overflow:hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; word-wrap: break-word; padding:3px 2px;">{{item.customerService}}</div>' },
				{ displayName: '合同号', field: 'contractNum', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.contractNum}}</div>' },
				{ displayName: '承运商', field: 'carrierName', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, enableSorting: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.carrierName}}</div>' },
				{ displayName: '承运商号码', field: 'carrierPhone', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, enableSorting: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.carrierPhone}}</div>' },
				{ displayName: '驾驶员号码', field: 'driverPhone', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, enableSorting: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.driverPhone}}</div>' },
				{ displayName: '车牌号', field: 'carryCarCode', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.carryCarCode}}</div>' },
				{ displayName: '合同状态', field: 'contractStatus', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.contractStatus}}</div>' },
				{ displayName: '油卡状态', field: 'oilCardStatus', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.oilCardStatus}}</div>' }
			],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope,(skipSize,pageSize)=>{
                    this.paginationChanged(skipSize,pageSize,this.$state);
                });
                // gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
                gridApi.core.notifyDataChange("options");
                gridApi.core.on.sortChanged(this.$scope, this.sortChange);
                gridApi.selection.on.rowSelectionChanged(this.$scope, this.selectChange);
            }
         }
        $('#opendataTime').click(() => {
		    $('#dataTime').datetimepicker('show');
		});
		$('#opendataTimeEnd').click(() => {
		    $('#dataTimeEnd').datetimepicker('show');
		});

        this.query();
        this.loadDropDownList();

    }

    localHistory():void{
        super.localHistory(this.$state)
    }
    getHistory():void{
        super.getHistory(this.$state,this.$location)
    }
    exportFunc=()=>{
        if(this.$scope.gridOptions.totalItems>30000){
            this.$ngBootbox.alert('导出数据不可超过3万条');
            return;
        }else{
            this.exportService.excelReceiptexport(this.orderBy.toString(),this.asc,"",this.queryTerms.clientName,this.queryTerms.route,this.queryTerms.shipStartTime,this.queryTerms.shipEndTime,"6,7","","",this.queryTerms.shipAddress,
            this.queryTerms.deliverAddress,this.queryTerms.carCode,this.queryTerms.contractNum,this.queryTerms.contractStatus,this.queryTerms.receiptPriceStatus,this.queryTerms.oilCardStatus,this.queryTerms.customerServiceId,"","",this.queryTerms.carrierName,
            this.queryTerms.receiptBillStatus);
            //新增查询条件 结算单据状态
            //this.queryTerms.receiptBillStatus
        }      
        
    }

    loadData(queryTerms:IReceiptManagentQueryTerms,skip:number,count:number):void{
        //新增查询条件 结算单据状态
        this.orderService.carryOrderList(this.orderBy.toString(),this.asc,"",queryTerms.clientName,queryTerms.route,queryTerms.shipStartTime,queryTerms.shipEndTime,"6,7","","",queryTerms.shipAddress,
        queryTerms.deliverAddress,queryTerms.carCode,queryTerms.contractNum,queryTerms.contractStatus,queryTerms.receiptPriceStatus,queryTerms.oilCardStatus,
        queryTerms.customerServiceId,"","","",queryTerms.carrierName,"","","",queryTerms.receiptBillStatus,"","",skip,count).then(result =>{
            // this.$scope.gridOptions.totalItems = result.data.total;
            this.$scope.gridOptions.data = result.data.data;
            /**
             * 设置列表高度
             */
            let gridHArr = 0;
            result.data.data.forEach((item,index) => { gridHArr =  gridHArr + item.orderList.length; });
            this.$scope.heightA = (gridHArr*39)+80;

            if (skip == 0) {this.$scope.gridOptions.paginationCurrentPage = 1;}
            this.skip = skip ;

                this.$scope.querying = false;
            }, error => {
                this.$scope.querying = false;
        });
    }


    getListCount():void{
        //新增查询条件 结算单据状态
        //this.$scope.queryTerms.receiptBillStatus
        this.orderService.carrierOrderCount("",this.$scope.queryTerms.clientName,this.$scope.queryTerms.route,this.$scope.queryTerms.shipStartTime,this.$scope.queryTerms.shipEndTime,"6,7","","",this.$scope.queryTerms.shipAddress,
        this.$scope.queryTerms.deliverAddress,this.$scope.queryTerms.carCode,this.$scope.queryTerms.contractNum,this.$scope.queryTerms.contractStatus,this.$scope.queryTerms.receiptPriceStatus,this.$scope.queryTerms.oilCardStatus,
        this.$scope.queryTerms.customerServiceId,"","","",this.$scope.queryTerms.carrierName,"","","",this.$scope.queryTerms.receiptBillStatus,"","").then(res=>{
            this.$scope.gridOptions.totalItems = res.data.extData;
        })
    }

    /**
     * 下拉列表
     */
    loadDropDownList():void{
        this.$scope.contractStatusDropDown = this.valueService.getContractStatusList().data.slice(1,3);
        this.$scope.oilCardStatusDropDown = this.valueService.getOilCCardStatusList().data;
        this.$scope.receiptPriceStatusDropDown = this.valueService.getReceiptStatusList().data;
        this.employeeService.getbytype("4",0,-1).then(result => {  //CommissionerType.CustomerService.toString()
            this.$scope.customerServiceDropDown = result.data.data;
        });

        //新增回单管理---结算单据状态下拉
        this.$scope.receiptBillStatusDropDown = this.valueService.getReceiptBillStatusDropDown().data
    }

    /**
     * 排序事件触发
     */
    sortChange = (grid: uiGrid.IGridInstanceOf<carryOrderListResponse>, sortColumns: Array<uiGrid.IGridColumnOf<carryOrderListResponse>>)=>{
        if (sortColumns.length == 0) {
            this.reload();
        } else {
            let sortItem = sortColumns[0];
            switch (sortItem.name) {
                case "orderId": {
                    this.orderBy = 1;
                } break;
                case "carryCarCode": {
                    this.orderBy = 2;
                } break;
                case "carLength": {
                    this.orderBy = 3;
                } break;
                case "shipTime": {
                    this.orderBy = 4;
                } break;
                case "startAddress": {
                    this.orderBy = 5;
                } break;
                case "endAddress": {
                    this.orderBy = 6;
                } break;
                case "goodsNum": {
                    this.orderBy = 14;
                } break;
                case "contractNum": {
                    this.orderBy = 8;
                } break;
                case "contractStatus":{
                    this.orderBy = 9;
                }break;
                case "oilCardStatus": {
                    this.orderBy = 10;
                } break;
                case "receiptOrderDegree": {
                    this.orderBy = 11;
                } break;
                case "clientName":{
                    this.orderBy = 12;
                }break;
                case "orderStatus":{
                    this.orderBy = 13;
                }
            }
            this.asc = sortItem.sort.direction == "asc";
            this.reload();
        }
    }

    /**
     * 单选事件
     */
    selectChange = (row: uiGrid.IGridRowOf<carryOrderListResponse>) => {
        (row.isSelected == true)?this.selectCarryOrderId = row.entity.id : this.selectCarryOrderId = "";
    }

    /**
     * 回单管理事件
     */
    receiptOrderDetail = ()=>{
        if (this.selectCarryOrderId != "") {
            this.orderService.carryOrder(this.selectCarryOrderId).then((res) => {
                if (res.data.orderList.length > 1) {
                    this.orderService.detail(res.data.orderList[0]).then((res) => {
                        if (res.data.orderStatus == 5) {
                            this.$ngBootbox.alert("待发货状态不能修改回单");
                            return;
                        } else {
                            this.$state.go("app.fee.receiptManagentBulk", { id: this.selectCarryOrderId, name: 'Edit'});
                        }
                    },(rej)=> {  });
                } else {
                    this.orderService.detail(res.data.orderList[0]).then((res) => {
                        if (res.data.orderStatus == 5) {
                            this.$ngBootbox.alert("待发货状态不能修改回单");
                            return;
                        } else {
                            this.$state.go("app.fee.receiptManagentOrder", { id: res.data.id, carrierOrderId: this.selectCarryOrderId, name: 'Edit'});
							}
						},(rej) => {  })
					}
				}, (rej)=> {  });
			}else{
                this.$ngBootbox.alert("请至少选择一条数据！");
                return;
            }
    }

    /**
     * 判断是否有回单权限
     */
    receiptOrder = () =>{
        this.authorizationService.auth("24E0A026891BC3907455D997D898E2F0C2AF7CB020383D43").then((res) => {
			this.$scope.canReceiptOrderDetail = res.data.extData;
		},(rej) => {  });
    }

    /**
     *  判断是否有导出权限
     */
    exportOrder = () => {
        this.authorizationService.auth("24E0A026891BC390D2F6C0FD8964BD8B001EF0AE84BBC09B60B462690F8BB3CC").then((res)=> {
			this.$scope.canExport = res.data.extData;
		},(rej)=> {  });
    }
}

angular.module("tms").controller("receiptManagentController", ["$scope","authorizationService","routeService","$state","orderService","valueService","employeeService","$ngBootbox","$location","exportService", ReceiptManagentController]);